//
//  BCSheetPickerView.m
//  fitness-iOS
//
//  Created by 卢仕彤 on 2018/1/6.
//  Copyright © 2018年 卢仕彤. All rights reserved.
//

#import "BCSheetPickerView.h"
#import "FFGlobalHeader.h"
#import "NSString+Timestamp.h"
#import "Province.h"

@interface BCSheetPickerView()<UIPickerViewDelegate,UIPickerViewDataSource>
@property (weak,nonatomic)UIView *bgView;    //屏幕下方看不到的view
@property (weak,nonatomic)UILabel *titleLabel; //中间显示的标题lab
@property (weak, nonatomic) UIPickerView *pickerView;
@property(nonatomic,strong)UIDatePicker *datePicker;
@property (weak,nonatomic)UIButton *cancelButton;
@property (weak,nonatomic)UIButton *doneButton;
@property (strong,nonatomic)NSArray *dataArray;   // 用来记录传递过来的数组数据
@property (strong,nonatomic)NSString *headTitle;  //传递过来的标题头字符串
@property (strong,nonatomic)NSString *backString; //回调的字符串
@property (assign,nonatomic)NSInteger selectNumber;
@end
@implementation BCSheetPickerView
+(instancetype)BCSheetStringPickerWithTitle:(NSArray *)title andHeadTitle:(NSString *)headTitle andSelectNumber:(NSInteger)selectNumber andSheetstyle:(Sheet_Style)style Andcall:(BCSheetPickerViewBlock)callBack
{
    BCSheetPickerView *pickerView = [[BCSheetPickerView alloc]initWithFrame:[UIScreen mainScreen].bounds andTitle:title andHeadTitle:headTitle andSelectNumber:selectNumber andSheetstyle:(Sheet_Style)style];
    pickerView.callBack = callBack;
    return pickerView;
}
- (instancetype)initWithFrame:(CGRect)frame andTitle:(NSArray*)title andHeadTitle:(NSString *)headTitle andSelectNumber:(NSInteger)selectNumber andSheetstyle:(Sheet_Style)style
{
    self = [super initWithFrame:frame];
    if (self) {
        self.dataArray = title;
        _headTitle = headTitle;
        _selectNumber = selectNumber;
        _backString = self.dataArray[selectNumber];
        _style = style;
        [self setupUI];
    }
    return self;
}
-(void)tap{
    
    [self dismissPicker];
}
-(void)setupUI
{
    //首先创建一个位于屏幕下方看不到的view
    UIView* bgView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    bgView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.7];
    UITapGestureRecognizer *g = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap)];
    [bgView addGestureRecognizer:g];
    [[[[UIApplication sharedApplication] delegate] window] addSubview:self];
    self.bgView = bgView;
    [self addSubview:bgView];
    
    ///pickview和取消、确定按钮
    UIView *pickandbtnView = [[UIView alloc]initWithFrame:CGRectMake(0, Main_Screen_Height - 250 , Main_Screen_Width, 250+4)];
    pickandbtnView.backgroundColor = [UIColor colorWithHexString:@"#F9F9F9"];
    [self addSubview:pickandbtnView];
    //  标题
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(Main_Screen_Width/2-75, 15, 150, 20)];
    titleLabel.font = [UIFont systemFontOfSize:18];
    [titleLabel setBackgroundColor:[UIColor clearColor]];
    [titleLabel setTextAlignment:NSTextAlignmentCenter];
    [titleLabel setText:_headTitle];
    [titleLabel setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
    [pickandbtnView addSubview:titleLabel];
    self.titleLabel = titleLabel;
    
    //取消按钮
    UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
    cancelButton.frame = CGRectMake(2, 15, Main_Screen_Width*0.2, 20);
    NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:@"取消" attributes:
                                      @{ NSForegroundColorAttributeName: [UIColor colorWithHexString:@"#333333"],
                                         NSFontAttributeName :           [UIFont systemFontOfSize:14],
                                         NSUnderlineStyleAttributeName : @(NSUnderlineStyleNone) }];
    [cancelButton setAttributedTitle:attrString forState:UIControlStateNormal];
    cancelButton.adjustsImageWhenHighlighted = NO;
    cancelButton.backgroundColor = [UIColor clearColor];
    [cancelButton addTarget:self action:@selector(clicked:) forControlEvents:UIControlEventTouchUpInside];
    [pickandbtnView addSubview:cancelButton];
    self.cancelButton = cancelButton;
    
    //完成按钮
    UIButton *doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
    doneButton.frame = CGRectMake(Main_Screen_Width-Main_Screen_Width*0.2-2, 15, Main_Screen_Width*0.2, 20);
    NSAttributedString *attrString2 = [[NSAttributedString alloc] initWithString:@"完成" attributes:
                                       @{ NSForegroundColorAttributeName: [UIColor colorWithHexString:@"#FA9516"],
                                          NSFontAttributeName :           [UIFont systemFontOfSize:14],
                                          NSUnderlineStyleAttributeName : @(NSUnderlineStyleNone) }];
    [doneButton setAttributedTitle:attrString2 forState:UIControlStateNormal];
    doneButton.adjustsImageWhenHighlighted = NO;
    doneButton.backgroundColor = [UIColor clearColor];
    [doneButton addTarget:self action:@selector(clicked:) forControlEvents:UIControlEventTouchUpInside];
    [pickandbtnView addSubview:doneButton];
    self.doneButton = doneButton;
    
    //选择器
    if (_style == SINGLEPICK) {
        UIPickerView *pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0,50, Main_Screen_Width, 200)];
        [pickerView setShowsSelectionIndicator:YES];
        [pickerView setDelegate:self];
        [pickerView setDataSource:self];
        pickerView.backgroundColor = [UIColor whiteColor];
        [pickandbtnView addSubview:pickerView];
        self.pickerView = pickerView;
        
        [pickerView selectRow:_selectNumber inComponent:0 animated:NO];
        self.pickerView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    }else if (_style == DATA_PICKER){
        _datePicker = [[UIDatePicker alloc]initWithFrame:CGRectMake(0,50, Main_Screen_Width, 200)];
        _datePicker.datePickerMode = UIDatePickerModeDate;
        _datePicker.backgroundColor = [UIColor whiteColor];
        NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
        _datePicker.locale = locale;
        _datePicker.maximumDate = [NSDate date];
        
        //        _datePicker.minimumDate = [NSDate dateWithTimeIntervalSince1970:0]
        _datePicker.minimumDate = [NSDate dateWithTimeIntervalSince1970:-20*365*24*60*60-5*24*60*60];
        //        [_datePicker addTarget:self action:@selector(dataPicker_changeValue) forControlEvents:UIControlEventValueChanged];
        [pickandbtnView addSubview:_datePicker];
    }
    self.autoresizingMask = UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleWidth;
}

//-(void)dataPicker_changeValue{
//    NSDate *date = _datePicker.date;
//    _backString =  [func getTimeFromNSDate:date];
//}
- (void)clicked:(UIButton *)sender
{
    if ([sender isEqual:self.cancelButton]) {
        [self dismissPicker];
    }else{
        if (self.callBack) {
            if (_datePicker) {
                NSDate *date = _datePicker.date;
                _backString =  [NSString getTimeFromNSDate:date];
            }
            self.callBack(self,_backString);
            [self dismissPicker];
        }
    }
}

#pragma mark - 该方法的返回值决定该控件包含多少列
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView*)pickerView
{
    return 1;
}

#pragma mark - 该方法的返回值决定该控件指定列包含多少个列表项
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    return self.dataArray.count;
}

#pragma mark - 该方法返回的NSString将作为UIPickerView中指定列和列表项的标题文本
//- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
//{
//    return self.dataArray[row];
//}

#pragma mark - 当用户选中UIPickerViewDataSource中指定列和列表项时激发该方法
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    //这个属性可以控制 标题栏。
    _backString = self.dataArray[row];
}
-(CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component{
    return 50;
}
- (UIView*)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    UILabel* l = [[UILabel alloc] init];
    l.textColor = self.textColor;
    l.textAlignment = NSTextAlignmentCenter;
    l.text = self.dataArray[row];
    
    for(UIView *line in pickerView.subviews)
    {
        if (line.frame.size.height < 1)
        {
            line.backgroundColor = [UIColor colorWithHexString:@"#E7E7E7"];
        }
    }
    
    return l;
}

- (UIColor *)textColor
{
    if (!_textColor) {
        _textColor = [UIColor blackColor];
    }
    return _textColor;
}

- (void)show
{
    [UIView animateWithDuration:0.8f delay:0 usingSpringWithDamping:0.9f initialSpringVelocity:0.7f options:UIViewAnimationOptionCurveEaseInOut | UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionLayoutSubviews animations:^{
        
        
    } completion:NULL];
}

- (void)dismissPicker
{
    [UIView animateWithDuration:0.8f delay:0 usingSpringWithDamping:0.9f initialSpringVelocity:0.7f options:UIViewAnimationOptionCurveEaseInOut | UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionLayoutSubviews animations:^{
        
        
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
        
    }];
}

@end

@interface BCSalaryPickerView ()<UIPickerViewDataSource,UIPickerViewDelegate>

@property (nonatomic, copy) CompletionBlock block;

@property (nonatomic, copy) NSString *leftSalaryString;
@property (nonatomic, copy) NSString *rightSalaryString;

@property (nonatomic, strong) NSMutableArray *leftSalaryArray;
@property (nonatomic, strong) NSMutableArray *rightSalaryArray;

@property (nonatomic, strong) UIPickerView * pickerView;
@end

@implementation BCSalaryPickerView

+ (void)showWithLeftSalary:(NSString *)leftSalaryString rightSalary:(NSString *)rightSalaryString completion:(CompletionBlock)block {
    BCSalaryPickerView *pickerView =[[self alloc] initWithFrame:[UIScreen mainScreen].bounds leftSalary:leftSalaryString rightSalary:rightSalaryString];
    pickerView.block = block;
    [[[UIApplication sharedApplication] keyWindow] addSubview:pickerView];
}

- (instancetype)initWithFrame:(CGRect)frame leftSalary:(NSString *)leftSalaryString  rightSalary:(NSString *)rightSalaryString {
    if (self = [super initWithFrame:frame]) {
        if ([leftSalaryString length] == 0) {
            self.leftSalaryString = @"";
            self.rightSalaryString = @"";
        } else {
            self.leftSalaryString = leftSalaryString;
            self.rightSalaryString = rightSalaryString;
        }
        [self initView];
    }
    return self;
}

#pragma mark
#pragma mark btn Action

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self removeFromSuperview];
}

- (void)cancelButtonClick {
    [self removeFromSuperview];
}
- (void)doneButtonClick {
    [self removeFromSuperview];
    if (self.block) {
        self.block(_leftSalaryString,_rightSalaryString);
    }
}

#pragma mark
#pragma mark - pickerView delegate And dataSource
//返回几列
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    
    return 3;
}

//返回列的行数
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    if (component == 0) {
        return _leftSalaryArray.count;
    }
    else if (component == 1) {
        return 1;
    }
    return _rightSalaryArray.count;
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
    UILabel* pickerLabel = (UILabel*)view;
    if (!pickerLabel){
        pickerLabel = [[UILabel alloc] init];
        pickerLabel.textColor = [UIColor colorWithHexString:@"#333333"];
        [pickerLabel setTextAlignment:NSTextAlignmentCenter];
        [pickerLabel setBackgroundColor:[UIColor clearColor]];
        [pickerLabel setFont:[UIFont systemFontOfSize:19]];
    }
    
    pickerLabel.text=[self pickerView:pickerView titleForRow:row forComponent:component];
    return pickerLabel;
}

//显示的标题
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    if (component == 0){
        return [NSString stringWithFormat:@"%@k",_leftSalaryArray[row]];
    }
    else if (component == 1) {
        return @"至";
    }
    return [NSString stringWithFormat:@"%@k",_rightSalaryArray[row]];
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    if (component == 0) {//刷新
        [pickerView selectRow:0 inComponent:2 animated:YES];
        [self getCorrectRightSalaryArrayWithLeftValue:self.leftSalaryArray[row]];
        [pickerView reloadComponent:2];
    }
    NSInteger leftComponentRow = [pickerView selectedRowInComponent:0];
    NSInteger rightComponentRow = [pickerView selectedRowInComponent:2];
    _leftSalaryString = [NSString stringWithFormat:@"%@",[_leftSalaryArray objectAtIndex:leftComponentRow]];
    _rightSalaryString = [NSString stringWithFormat:@"%@",[_rightSalaryArray objectAtIndex:rightComponentRow]];
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component {
    return 50;
}

#pragma mark- initView

- (void)initView {
    
    self.backgroundColor = [UIColor colorWithHexString:@"#000000" alpha:0.7];
    UIView *backGroudView =[[UIView alloc]init];
    backGroudView.frame = CGRectMake(0, Main_Screen_Height - 250, Main_Screen_Width, 250);
    backGroudView.backgroundColor =[UIColor whiteColor];
    [self addSubview:backGroudView];
    
    UIView *toolBarView = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, Main_Screen_Width, 50)];
    toolBarView.backgroundColor =[UIColor colorWithHexString:@"#f9f9f9"];
    [backGroudView addSubview:toolBarView];
    
    UIButton * cancelButton =[UIButton buttonWithType:UIButtonTypeCustom];
    [cancelButton setTitle:@"取消" forState:UIControlStateNormal];
    cancelButton.frame = CGRectMake(17, 0, 64, 50);
    cancelButton.titleLabel.font = [UIFont systemFontOfSize:16];
    [cancelButton setTitleColor:[UIColor colorWithHexString:@"#333333"] forState:UIControlStateNormal];
    [cancelButton addTarget:self action:@selector(cancelButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [toolBarView addSubview:cancelButton];
    
    UIButton *doneButton =[UIButton buttonWithType:UIButtonTypeCustom];
    doneButton.titleLabel.font = [UIFont systemFontOfSize:16];
    [doneButton setTitle:@"完成" forState:UIControlStateNormal];
    doneButton.frame = CGRectMake(Main_Screen_Width-81, 0, 64, 50);
    [doneButton setTitleColor:[UIColor colorWithHexString:@"#fa9416"] forState:UIControlStateNormal];
    [doneButton addTarget:self action:@selector(doneButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [toolBarView addSubview:doneButton];
    
    _leftSalaryArray = [NSMutableArray array];
    _rightSalaryArray = [NSMutableArray array];
    for (NSInteger k = 1 ; k <= 100; k++) {
        [_leftSalaryArray addObject:[NSString stringWithFormat:@"%ld",k]];
    }
    
    self.pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 44, Main_Screen_Width, 200)];
    self.pickerView.delegate = self;
    self.pickerView.dataSource = self;
    [backGroudView addSubview:self.pickerView];
    
    if ([_leftSalaryString length] == 0) {
        [self.pickerView selectRow:4 inComponent:0 animated:NO];
        [self pickerView:self.pickerView didSelectRow:4 inComponent:0];
    }
    else {
        [self getCorrectRightSalaryArrayWithLeftValue:_leftSalaryString];
        [self.pickerView selectRow:[_leftSalaryString integerValue]-1 inComponent:0 animated:NO];
        [self.pickerView selectRow:[_rightSalaryString integerValue]-[_leftSalaryString integerValue]-1 inComponent:2 animated:NO];
    }
}

- (void)getCorrectRightSalaryArrayWithLeftValue:(NSString *)leftSelectString {
    if ([_rightSalaryArray count] > 0) {
        [_rightSalaryArray removeAllObjects];
    }
    NSInteger firstComponentValue = [leftSelectString integerValue];
    if (firstComponentValue < 50) {
        for (NSInteger i = firstComponentValue + 1; i <= firstComponentValue * 2; i++) {
            [_rightSalaryArray addObject:[NSString stringWithFormat:@"%ld",i]];
        }
    }
    else {
        NSInteger endValue = firstComponentValue * 2;
        if (endValue > 150) {
            endValue = 150;
        }
        for (NSInteger i = firstComponentValue + 10; i <= endValue;) {
            [_rightSalaryArray addObject:[NSString stringWithFormat:@"%ld",i]];
            i+=10;
        }
    }
}

@end

@interface AddressPickerView () <UIPickerViewDataSource, UIPickerViewDelegate>

@property (nonatomic, copy) backInfoBlock block;
@property (nonatomic, copy) NSString *provinceString;
@property (nonatomic, copy) NSString *cityString;
@property (nonatomic, copy) NSString *areasString;
@property (nonatomic, strong) UIPickerView * pickerView;

@property (nonatomic ,strong) NSMutableArray * pArr;/**< 地址选择器数据源,装省份模型,每个省份模型内包含城市模型*/

@property (nonatomic ,strong) NSDictionary   * dataDict;/**< 省市区数据源字典*/
@property (nonatomic ,strong) NSMutableArray * provincesArr;/**< 省份名称数组*/
@property (nonatomic ,strong) NSDictionary   * citysDict;/**< 所有城市的字典*/
@property (nonatomic ,strong) NSDictionary   * areasDict;/**< 所有地区的字典*/

@end

@implementation AddressPickerView

+ (void)showAddressWithConpletion:(backInfoBlock)block {
    
    AddressPickerView *pickerView =[[self alloc] initWithFrame:[UIScreen mainScreen].bounds];
    pickerView.block = block;
    [[[UIApplication sharedApplication] keyWindow] addSubview:pickerView];
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self loadJsonAndData];
        [self initView];
    }
    return self;
}

- (void)initView {
    self.backgroundColor = [UIColor colorWithHexString:@"#000000" alpha:0.7];
    UIView *backGroudView =[[UIView alloc]init];
    backGroudView.frame = CGRectMake(0, Main_Screen_Height - 250, Main_Screen_Width, 250);
    backGroudView.backgroundColor =[UIColor whiteColor];
    [self addSubview:backGroudView];
    
    UIView *toolBarView = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, Main_Screen_Width, 50)];
    toolBarView.backgroundColor =[UIColor colorWithHexString:@"#f9f9f9"];
    [backGroudView addSubview:toolBarView];
    
    UIButton * cancelButton =[UIButton buttonWithType:UIButtonTypeCustom];
    [cancelButton setTitle:@"取消" forState:UIControlStateNormal];
    cancelButton.frame = CGRectMake(17, 0, 64, 50);
    cancelButton.titleLabel.font = [UIFont systemFontOfSize:16];
    [cancelButton setTitleColor:[UIColor colorWithHexString:@"#333333"] forState:UIControlStateNormal];
    [cancelButton addTarget:self action:@selector(cancelButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [toolBarView addSubview:cancelButton];
    
    UIButton *doneButton =[UIButton buttonWithType:UIButtonTypeCustom];
    doneButton.titleLabel.font = [UIFont systemFontOfSize:16];
    [doneButton setTitle:@"完成" forState:UIControlStateNormal];
    doneButton.frame = CGRectMake(Main_Screen_Width-81, 0, 64, 50);
    [doneButton setTitleColor:[UIColor colorWithHexString:@"#fa9416"] forState:UIControlStateNormal];
    [doneButton addTarget:self action:@selector(doneButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [toolBarView insertSubview:doneButton atIndex:1000];
    
    self.pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 44, Main_Screen_Width, 200)];
    self.pickerView.delegate = self;
    self.pickerView.dataSource = self;
    [backGroudView addSubview:self.pickerView];
    
}
#pragma mark btn Action

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self removeFromSuperview];
}

- (void)cancelButtonClick {
    [self removeFromSuperview];
}
- (void)doneButtonClick {
    [self removeFromSuperview];
    if (self.block) {
        
        NSInteger selectProvince = [self.pickerView selectedRowInComponent:0];
        NSInteger selectCity     = [self.pickerView selectedRowInComponent:1];
        NSInteger selectArea     = [self.pickerView selectedRowInComponent:2];
        
        Province * p = _pArr[selectProvince];
        //解决省市同时滑动未结束时点击完成按钮的数组越界问题
        if (selectCity > p.cityModels.count - 1) {
            selectCity = p.cityModels.count - 1;
        }
        
        City * c = p.cityModels[selectCity];
        //解决省市区同时滑动未结束时点击完成按钮的数组越界问题
        if (selectArea > c.areas.count - 1) {
            selectArea = c.areas.count - 1;
        }
        
        self.block(p.name,c.cityName,c.areas[selectArea]);
    }
}
- (void)loadJsonAndData {
    NSString * filePath = [[NSBundle mainBundle] pathForResource:@"address"
                                                          ofType:@"txt"];
    
    NSError  * error;
    NSString * str22 = [NSString stringWithContentsOfFile:filePath
                                                 encoding:NSUTF8StringEncoding
                                                    error:&error];
    
    if (error) {
        return;
    }
    
    _dataDict = [self dictionaryWithJsonString:str22];
    
    if (!_dataDict) {
        return;
    }
    
    _provincesArr = [_dataDict objectForKey:@"p"];
    _citysDict    = [_dataDict objectForKey:@"c"];
    _areasDict    = [_dataDict objectForKey:@"a"];
    
    _pArr         = [[NSMutableArray alloc]init];
    
    //省份模型数组加载各个省份模型
    for (int i = 0 ;i < _provincesArr.count; i++) {
        NSArray  * citys = [_citysDict objectForKey:_provincesArr[i]];
        Province * p     = [Province provinceWithName:_provincesArr[i]
                                               cities:citys];
        [_pArr addObject:p];
    }
    
    //各个省份模型加载各自的所有城市模型
    for (Province * p in _pArr) {
        NSMutableArray * areasArr = [[NSMutableArray alloc]init];
        for (NSString * cityName in p.cities) {
            NSString * cityKey = [NSString stringWithFormat:@"%@-%@",p.name,cityName];
            NSArray  * cityArr = [_areasDict objectForKey:cityKey];
            City     * city    = [City cityWithName:cityName areas:cityArr];
            [areasArr addObject:city];
        }
        p.cityModels = areasArr;
    }
}

- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    
    NSData  * jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError * err;
    NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                         options:NSJSONReadingMutableContainers
                                                           error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

#pragma mark - UIPickerDatasource
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 3;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    
    if (0 == component) {
        return _pArr.count;
    }
    else if (1 == component){
        NSInteger selectProvince = [pickerView selectedRowInComponent:0];
        Province  * p            = _pArr[selectProvince];
        return p.cities.count;
    }
    else if (2 == component){
        NSInteger selectProvince = [pickerView selectedRowInComponent:0];
        NSInteger selectCity     = [pickerView selectedRowInComponent:1];
        Province  * p            = _pArr[selectProvince];
        if (selectCity > p.cityModels.count - 1) {
            return 0;
        }
        City * c = p.cityModels[selectCity];
        return c.areas.count;
    }
    
    return 0;
}

#pragma mark - UIPickerViewDelegate
#pragma mark 填充文字
- (NSString *)pickerView:(UIPickerView *)pickerView
             titleForRow:(NSInteger)row
            forComponent:(NSInteger)component{
    
    if (0 == component) {
        Province * p = _pArr[row];
        return p.name;
    }
    
    else if (1 == component) {
        Province * selectP = _pArr[[pickerView selectedRowInComponent:0]];
        if (row > selectP.cities.count - 1) {
            return nil;
        }
        return selectP.cities[row];
    }
    else if (2 == component) {
        NSInteger selectProvince = [pickerView selectedRowInComponent:0];
        NSInteger selectCity     = [pickerView selectedRowInComponent:1];
        Province  * p            = _pArr[selectProvince];
        if (selectCity > p.cityModels.count - 1) {
            return nil;
        }
        City * c = p.cityModels[selectCity];
        if (row > c.areas.count -1 ) {
            return nil;
        }
        return c.areas[row];
    }
    return nil;
}
#pragma mark pickerView被选中
- (void)pickerView:(UIPickerView *)pickerView
      didSelectRow:(NSInteger)row
       inComponent:(NSInteger)component{
    if (0 == component) {
        NSInteger selectCity = [pickerView selectedRowInComponent:1];
        NSInteger selectArea = [pickerView selectedRowInComponent:2];
        [pickerView reloadComponent:1];
        [pickerView selectRow:selectCity inComponent:1 animated:YES];
        [pickerView reloadComponent:2];
        [pickerView selectRow:selectArea inComponent:2 animated:YES];
        
    }
    else if (1 == component){
        NSInteger selectArea = [pickerView selectedRowInComponent:2];
        [pickerView reloadComponent:2];
        [pickerView selectRow:selectArea inComponent:2 animated:YES];
    }
}

- (UIView *)pickerView:(UIPickerView *)pickerView
            viewForRow:(NSInteger)row forComponent:(NSInteger)component
           reusingView:(UIView *)view{
    
    UILabel* pickerLabel = (UILabel*)view;
    
    if (!pickerLabel){
        pickerLabel = [[UILabel alloc] init];
        pickerLabel.textColor = [UIColor colorWithRed:51.0/255
                                                green:51.0/255
                                                 blue:51.0/255
                                                alpha:1.0];
        pickerLabel.adjustsFontSizeToFitWidth = YES;
        [pickerLabel setTextAlignment:NSTextAlignmentCenter];
        [pickerLabel setBackgroundColor:[UIColor clearColor]];
        [pickerLabel setFont:[UIFont boldSystemFontOfSize:15]];
    }
    
    pickerLabel.text = [self pickerView:pickerView
                            titleForRow:row
                           forComponent:component];
    return pickerLabel;
}


@end

